//
//  ZHFNetworkManager.swift
//  zhihuifan
//
//  Created by apple on 2017/8/15.
//  Copyright © 2017年 youyou. All rights reserved.
//
import UIKit
import AFNetworking
fileprivate let BaseURL = "http://www.xftb168.com/"
enum RequestMethod {
    case GET
    case POST
}
class ZHFNetworkManager: AFHTTPSessionManager {
//创建网络管理工具单例
    static let shared:ZHFNetworkManager = {
        let instance = ZHFNetworkManager()
        // 设置响应反序列化支持的数据类型
        let set = NSSet(array: ["application/json", "text/html","text/json","text/javascript","text/plain"]);
        instance.responseSerializer.acceptableContentTypes = set as? Set<String>
        instance.requestSerializer = AFJSONRequestSerializer()
        return instance
    }()
    /// 令牌请求网络数据
    var access_token:String?
    func tokenRequest(requestMethod:RequestMethod = .GET,urlString:String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()){
        guard let accesstoken = access_token else {
            //FIXME:未登陆
            completion(nil,false)
            return
        }
       var parameter = parameters
        if parameter == nil {
            parameter = [String:AnyObject]()
        }
        parameter?["tokenid"] = accesstoken as AnyObject
        request(requestMethod: requestMethod, urlString: urlString, parameters: parameters, completion: completion)
    }
    func request(requestMethod:RequestMethod = .GET,urlString:String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()){
        
        let success = {(task:URLSessionTask?,json:Any?) -> () in

            completion((json as AnyObject), true)
        }
        let failure = {(task:URLSessionTask?,error:Error?) -> () in
            
            completion(nil, false)
        }
        let urlString = BaseURL + urlString
        
        if requestMethod == .GET {
            get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
           post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
//          let request =   AFJSONRequestSerializer().request(withMethod: "POST", urlString: urlString, parameters: parameters, error: NSErrorPointer.none)
            
        }
    }
}
